package com.vvvtimes.demo.service;

import cn.hutool.core.codec.Base64;
import cn.hutool.core.net.URLDecoder;
import cn.hutool.extra.qrcode.QrCodeUtil;
import com.vvvtimes.demo.common.dto.RestResponse;
import com.vvvtimes.demo.domain.dto.DecoderDTO;
import com.vvvtimes.demo.domain.dto.EncoderDTO;
import com.vvvtimes.demo.domain.dto.UrlDecoderDTO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.nio.charset.Charset;


@Slf4j
@Service
public class DecoderService {

    public RestResponse<String> base64Encoder(DecoderDTO decoderDTO) {
        RestResponse<String> result = new RestResponse<>();
        String data = decoderDTO.getData();
        String res = Base64.decodeStr(data);
        result.setResult(res);
        return result;
    }

    public RestResponse<String> urlDecoder(UrlDecoderDTO decoderDTO) {
        RestResponse<String> result = new RestResponse<>();
        String data = decoderDTO.getData();
        String charset = decoderDTO.getCharset();
        if (charset == null) {
            charset = "utf-8";
        }
        String res = URLDecoder.decode(data, Charset.forName(charset));
        result.setResult(res);
        return result;
    }

    public RestResponse<String> qrDecoder(MultipartFile file) {
        RestResponse<String> result = new RestResponse<>();
        // 将MultipartFile转换为BufferedImage
        BufferedImage bufferedImage = null;
        try {
            bufferedImage = ImageIO.read(file.getInputStream());
            // 对BufferedImage进行灰度处理
            BufferedImage grayImage = convertToGrayscale(bufferedImage);
            /*解析灰度图片*/
            String decode = QrCodeUtil.decode(grayImage);
            log.info("解析出的数据-----{}", decode);
            result.setResult(decode);
        } catch (IOException e) {
            e.printStackTrace();
            log.info("解析数据失败", e);
        }
        return result;
    }


    //灰度处理
    private static BufferedImage convertToGrayscale(BufferedImage originalImage) {
        int width = originalImage.getWidth();
        int height = originalImage.getHeight();
        BufferedImage grayImage = new BufferedImage(width, height, BufferedImage.TYPE_BYTE_GRAY);
        for (int y = 0; y < height; y++) {
            for (int x = 0; x < width; x++) {
                int rgb = originalImage.getRGB(x, y);
                Color color = new Color(rgb);
                int gray = (int) (color.getRed() * 0.299 + color.getGreen() * 0.587 + color.getBlue() * 0.114);
                Color grayColor = new Color(gray, gray, gray);
                grayImage.setRGB(x, y, grayColor.getRGB());
            }
        }
        return grayImage;

    }
}
